﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraTab;

namespace BuildHelper.Scheduler
{
    public partial class FormMultiTask : XtraForm
    {
        public FormMultiTask()
        {
            InitializeComponent();
        }
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            if (!this.IsDesignMode())
            {
                Zadanie.PrepareLookupForZadania(rep_WRK_ZAD_ZADANIE);
            }
        }

        private void rep_WRK_ZAD_ZADANIE_EditValueChanged(object sender, EventArgs e)
        {
            DataRow r = gvZadania.GetFocusedDataRow();
            if (r != null)
            {
                int numer = r["WRK_ZAD_ID"].AsInt();
                DeleteZadanie(numer);
                BaseEdit ed = sender as BaseEdit;
                if(ed!=null)
                AddZadanie(r, ed.EditValue.AsString());
            }
        }

        private void DeleteZadanie(int numer)
        {
            XtraTabPage t = null;
            foreach (XtraTabPage tab in tabZadania.TabPages)
            {
                if (tab.Tag.AsString() == numer.AsString())
                {
                    t = tab;
                    break;
                }
            }
            if (t != null)
            {
                tabZadania.BeginInit();
                tabZadania.TabPages.Remove(t);
                if (t.Controls.Count > 0)
                    t.Controls[0].Dispose();
                t.Dispose();
                tabZadania.EndInit();
            }
        }
        private void AddZadanie(DataRow r, bool newRow)
        {
            AddZadanie(r, r["WRK_ZAD_ZADANIE"].AsString(), newRow);
        }
        private void AddZadanie(DataRow r, string zadanie, bool newRow = true)
        {
            if (zadanie.IsNull())
                return;
            int numer = r["WRK_ZAD_ID"].AsInt();
            ZadanieParamsControl ctrl = null;
            switch (zadanie)
            {
                case BuildHelper.Scheduler.Zadanie.ZadaniaId.BudowanieGui:
                    ctrl = new ZadanieGuiBuild();
                    break;
                case BuildHelper.Scheduler.Zadanie.ZadaniaId.BudowanieJavy:
                    ctrl = new ZadanieJavaBuild();
                    break;
                case BuildHelper.Scheduler.Zadanie.ZadaniaId.Info:
                    ctrl = new ZadanieInfo();
                    break;
                case BuildHelper.Scheduler.Zadanie.ZadaniaId.InternalSdk:
                    ctrl = new ZadanieInternalSDK();
                    break;
                case BuildHelper.Scheduler.Zadanie.ZadaniaId.TortoiseUpdate:
                    ctrl = new ZadanieTortoiseUpdate();
                    break;
                case BuildHelper.Scheduler.Zadanie.ZadaniaId.UaktualnianieBazDanych:
                    ctrl = new ZadanieDBUpdate();
                    break;
                case BuildHelper.Scheduler.Zadanie.ZadaniaId.UaktualnianieSrodowisk:
                    ctrl = new ZadanieEnvUpdate();
                    break;
            }
            if (ctrl != null)
            {
                XtraTabPage page = new XtraTabPage();
                page.Name = "page" + (numer * -1).AsString();
                page.Text = Zadanie.Zadania[zadanie].Nazwa;
                page.PageVisible = true;
                page.Tag = numer;
                page.Controls.Add(ctrl);
                tabZadania.TabPages.Add(page);
                tabZadania.SelectedTabPage = page;
                ctrl.OtherModeProvider = modeProvider1;
                if (newRow)
                {
                    ctrl.Row = r;
                    ctrl.InitEvents();
                    ctrl.SetDefault();
                }
                else
                {
                    ctrl.SetDefault();
                    ctrl.Row = r;
                    ctrl.InitEvents();
                    if (!newRow)
                        ctrl.SetControlsFromRow(Zadanie.Zadania[zadanie]);
                }
            }
        }

        private void modeProvider1_DeleteRow(object sender, ProgNetComponentsDx.Mode.DeleteRowEventArgs e)
        {
            if (e.Row != null)
            {
               
                int numer = e.Row["WRK_ZAD_ID"].AsInt();
                DeleteZadanie(numer);
                
                e.Row.Delete();
                e.Cancel = true;
                
                FocusTab(gvZadania.GetFocusedDataRow());
            }
        }

        private void btnUruchom_Click(object sender, EventArgs e)
        {
            RunZadania();
        }

        private void RunZadania()
        {
            if (ValidateAll())
            {
                DataRow[] rows = zadaniaDataSet.WRK_ZADANIA.Select(null, "POZYCJA", DataViewRowState.CurrentRows);
                if (rows.Length > 0)
                {
                    string zadanie;
                    Zadanie z;
                    modeProvider1.CurrentMode = ProgNetComponentsDx.Enums.FormMode.Read;
                    foreach (DataRow r in rows)
                    {
                        zadanie = r["WRK_ZAD_ZADANIE"].AsString();
                        z = Zadanie.Zadania[zadanie];
                        if (z != null)
                        {
                            List<string> list = new List<string>();
                            for (int i = 1; i < Zadanie.MAX_PARAMS; i++)
                                list.Add(r["WRK_ZAD_PARAM" + i].AsString());

                            r["STATUS"] = Zadanie.Statusy.W_Trakcie;

                            z.Action.DynamicInvoke(z.GetRealParams(r, list.ToArray()));
                            if (z.IsRowParam)
                            {
                                while (r["STATUS"].AsString() == Zadanie.Statusy.W_Trakcie)
                                {
                                    if (Program.IsExit)
                                        return;
                                    Application.DoEvents();
                                }
                                if (r["STATUS"].AsString() == Zadanie.Statusy.Blad)
                                {
                                    break;
                                }
                            }
                            else
                            {
                                r["STATUS"] = Zadanie.Statusy.Nieznany;
                            }
                        }
                    }
                    modeProvider1.CurrentMode = ProgNetComponentsDx.Enums.FormMode.Edit;
                }
                else
                {
                    this.ShowDxInfoDialog("Brak zadań");
                }
            }
        }

        private bool ValidateAll()
        {
            if (true)
            {

            }
            bool res = true;
            zadaniaDataSet.WRK_ZADANIA.ClearErrors();
            ZadanieParamsControl c;
            foreach (XtraTabPage page in tabZadania.TabPages)
            {
                if (page.Controls.Count > 0 && page.Controls[0] is ZadanieParamsControl)
                {
                    c = page.Controls[0] as ZadanieParamsControl;
                    if (!c.ValidateAll())
                    {
                        tabZadania.SelectedTabPage = page;
                        c.Row.SetColumnError("WRK_ZAD_ZADANIE", "Nie wszystkie dane są poprawne");
                        res = false;
                        break;
                    }
                }
            }
            return res;
        }

        private void gvZadania_FocusedRowChanged(object sender, DevExpress.XtraGrid.Views.Base.FocusedRowChangedEventArgs e)
        {
            DataRow r = gvZadania.GetDataRow(e.FocusedRowHandle);
            FocusTab(r);
        }
        private void FocusTab(DataRow r)
        {
            if (r != null)
            {
                foreach (XtraTabPage p in tabZadania.TabPages)
                {
                    if ((p.Controls[0] as ZadanieParamsControl).Row == r)
                    {
                        if (tabZadania.SelectedTabPage != p)
                            tabZadania.SelectedTabPage = p;
                        return;
                    }
                }
            }
        }
        private void tabZadania_SelectedPageChanged(object sender, TabPageChangedEventArgs e)
        {
            for (int i = 0; i < gvZadania.RowCount; i++)
            {
                DataRow r = gvZadania.GetDataRow(i);
                if (r != null && e.Page.Controls.Count > 0 && (e.Page.Controls[0] as ZadanieParamsControl).Row == r)
                {
                    if (gvZadania.FocusedRowHandle != i)
                        gvZadania.FocusedRowHandle = i;
                    return;
                }
            }
        }

        private void templateControl1_TemplateRead(object sender, EventArgs e)
        {
            foreach (DataRow r in zadaniaDataSet.WRK_ZADANIA.Select(null,null, DataViewRowState.CurrentRows))
            {
                r["STATUS"] = DBNull.Value;
            }
        }
        private void AddAll(DataRow[] rows)
        {
            DataRow nr;
            foreach (DataRow r in rows)
            {
                nr = zadaniaDataSet.WRK_ZADANIA.NewRow();
                CopyItemArray(r, nr);
                zadaniaDataSet.WRK_ZADANIA.Rows.Add(nr);
                AddZadanie(nr, false);
            }
            nr = gvZadania.GetFocusedDataRow();
            FocusTab(nr);
        }
        private void Clear()
        {
            foreach (DataRow r in zadaniaDataSet.WRK_ZADANIA.Select(null, null, DataViewRowState.CurrentRows))
            {
                DeleteZadanie(r["WRK_ZAD_ID"].AsInt());
            }
            this.zadaniaDataSet.WRK_ZADANIA.Clear();
        }
        private void templateControl1_AddingTemplate(object sender, Work.Template.MergingDataSetEventArgs e)
        {
            DataRow[] rows = e.TemplateDataSet.Tables["WRK_ZADANIA"].Select(null, "POZYCJA", DataViewRowState.CurrentRows);
            int ct = zadaniaDataSet.WRK_ZADANIA.Select(null,null, DataViewRowState.CurrentRows).Length;
            foreach (DataRow r in rows)
                r["POZYCJA"] = r["POZYCJA"].AsInt() + ct;

            AddAll(rows);
           
            e.Handeled = true;
        }

        private void templateControl1_ReadingTemplate(object sender, Work.Template.MergingDataSetEventArgs e)
        {
            Clear();

            DataRow[] rows = e.TemplateDataSet.Tables["WRK_ZADANIA"].Select(null, "POZYCJA", DataViewRowState.CurrentRows);
            
            AddAll(rows);
           
            e.Handeled = true;
        }

        private void CopyItemArray(DataRow source, DataRow dest)
        {
            foreach (DataColumn c in source.Table.Columns)
            {
                if (c.ColumnName != "WRK_ZAD_ID" && 
                    c.ColumnName != "STATUS")
                {
                    dest[c.ColumnName] = source[c.ColumnName];
                }
            }
        }

        private void btnClear_Click(object sender, EventArgs e)
        {
            Clear();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {

        }
        
    }
}
